import Vue from "vue";
import Component from "vue-class-component";
Component.registerHooks([
  "beforeRouteEnter",
  "beforeRouteLeave",
  "beforeRouteUpdate"
]);

import "./plugin";
import micAppConfig from "@/qiankun/config";
import "@/utils/openApiOption";
import App from "@/App.vue";
// import App from "@/configPrefix.vue";
import store from "@/store";
import router from "@/router/index";
import "@/router/guard/permission";
import initPublicPath from "@/qiankun/public-path";
import startMicFrontEndMainApp from "@/qiankun/mainapp";
import VueRouter from "vue-router";
import { micAppTypes } from "./qiankun/micAppTypes/model/appTypes";
import initGlobalStore from "./qiankun/initGlobalStore";
import { MicAppProps } from "./qiankun/micAppTypes/micappProps";

let myRouter: VueRouter | undefined = router;
if (micAppConfig.appType !== micAppTypes.ROOT) {
  initPublicPath();
  initGlobalStore();
}
if (micAppConfig.appType !== micAppTypes.CHILD) startMicFrontEndMainApp();

let appInstance: Vue | null = null;
function render(props?: MicAppProps) {
  //启动vue应用
  const container = props?.container;
  let node: Element | null = null;

  if (container && typeof container != "string") {
    node = container.querySelector("#app");
  }

  appInstance = new Vue({
    router: myRouter,
    store,
    render: h => h(App)
  }).$mount(node ? node : "#app");
}

if (
  !window.__POWERED_BY_QIANKUN__ ||
  micAppConfig.appType === micAppTypes.ROOT
) {
  // 独立运行
  render();
}

export function getAppInstance() {
  return appInstance;
}
export async function bootstrap() {
  console.log("作为子应用启动");
}
export async function mount(
  // props: MicroAppStateActions & { container?: HTMLElement }
  props: MicAppProps
) {
  // 作为子应用挂载
  console.log("作为子应用挂载", props);
  // props.onGlobalStateChange((state, prev) => {
  //   // state: 变更后的状态; prev 变更前的状态
  //   console.log("子应用监听全局状态机");
  // });
  props.eventBus.operation.$emit("ok");
  render(props);
}
export async function unmount() {
  // 作为子应用卸载
  if (appInstance) {
    appInstance.$destroy();
    appInstance.$el.innerHTML = "";
    appInstance = null;
    // myRouter = null;
  }
}
